//
//  TSBaseVC.swift
//  TSLiveWallpaper
//
//  Created by 100Years on 2024/12/20.
//

import UIKit
import Combine

open class TSBaseVC: UIViewController {
  
    public var closePageComplete:(()->Void)?
    
    public var cancellable: [AnyCancellable] = []
    
    public var blurEffect: UIBlurEffect?
    public lazy var navBlurView: UIVisualEffectView = {
        let view = UIVisualEffectView()
        return view
    }()
    
    public lazy var contentView: UIView = {
        let view = UIView()
        return view
    }()
    
    
    public lazy var baseNavContentBarView = TSBaseNavContentBarView()
    
    public lazy var navBarContentView: UIView = {
        let view = UIView()
        view.backgroundColor = .clear
        return view
    }()
    
    public lazy var normalNavBarView: TSNormalNavigationBarView = {
        let view = TSNormalNavigationBarView()
        return view
    }()
    
    
    public lazy var viewBgImageView: UIImageView = {
        let view = UIImageView()
        view.backgroundColor = .clear
        return view
    }()

    public lazy var netWorkView: UIView = {
        let view = UIView()
        view.backgroundColor = .clear
        return view
    }()
    
    public lazy var fullView: UIView = {
        let fullView = UIView()
        fullView.frame = UIScreen.main.bounds
        fullView.backgroundColor = .clear
        return fullView
    }()
    
    public lazy var contentScrollViewContent = UIView()
    public lazy var contentScrollView: UIScrollView = {
        let contentScrollView = UIScrollView()
        contentScrollView.contentInsetAdjustmentBehavior = .never
        contentScrollView.translatesAutoresizingMaskIntoConstraints = false
        contentScrollView.showsVerticalScrollIndicator = false
        contentScrollView.showsHorizontalScrollIndicator = false
        return contentScrollView
    }()
    

    public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }

    required public init?(coder: NSCoder) {
        super.init(coder: coder)
    }

    /// 提供一个无参数的默认初始化方法
    public init() {
        super.init(nibName: nil, bundle: nil)
    }
    
    open override func viewDidLoad() {
        super.viewDidLoad()
        setupSuperSomeView()
        createData()
        createView()
        createFrame()
        dealThings()
    }
    
    private func setupSuperSomeView() {
        edgesForExtendedLayout = [.all]
        
        view.addSubview(fullView)
        fullView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        fullView.addSubview(contentView)
        fullView.addSubview(navBarContentView)
        
        contentView.snp.makeConstraints { make in
            make.top.equalTo(k_Nav_Height)
            make.leading.trailing.bottom.equalToSuperview()
        }
        
        navBarContentView.snp.makeConstraints { make in
            make.leading.top.trailing.equalToSuperview()
            make.height.equalTo(k_Nav_Height)
        }

        view.backgroundColor = TSColorConfigShared.mainBg
        view.layoutIfNeeded()
    }
    
    
    public func setViewBgImageNamed(named:String){
        if viewBgImageView.superview == nil {
            view.insertSubview(viewBgImageView, at: 0)
            viewBgImageView.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
        }
        viewBgImageView.image = UIImage(named: named)
    }
    
    
    //子类重写
    open func createData(){}
    open func createView(){}
    open func createFrame(){}
    open func dealThings(){}
    

    public func addNormalNavBarView(){
        if normalNavBarView.superview == nil {
            navBarContentView.addSubview(normalNavBarView)
            normalNavBarView.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
        }
    }

    public func addBaseNavContentBarView(){
        if baseNavContentBarView.superview == nil {
            navBarContentView.addSubview(baseNavContentBarView)
            baseNavContentBarView.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
        }
    }
    

    open override func viewWillAppear(_ animated: Bool) {
        debugPrint("进入------>\(String(describing: type(of: self)))")
    }

    
    func deinitHandle(){
        NotificationCenter.default.removeObserver(self)
        cancellable.removeAll()
        closePageComplete?()
        debugPrint("♻️♻️♻️ TGRootViewController -> \(type(of: self)) deinit ♻️♻️♻️")
    }
    
    deinit {
        deinitHandle()
    }

    // MARK: - 导航栏方法

    public func setTitleText(_ title: String,image:UIImage? = nil,spacing:CGFloat = 0,imageRight:Bool = false) -> UIButton {
        addNormalNavBarView()
        let titleNavBtn = normalNavBarView.setTitleName(title)
        UIButton.createButton()
        if let image = image {
            titleNavBtn.setImage(image, for: .normal)
        }
        titleNavBtn.semanticContentAttribute = imageRight ? .forceRightToLeft : .forceLeftToRight // 确保布局方向
        titleNavBtn.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: spacing) // 只调整 title 的 left
        titleNavBtn.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -spacing) // 只调整 image 的 right
        return titleNavBtn
    }
    
    public func setPageTitle(_ title: String,backImageNamed:String? = nil) {
        let pageTitle = title
        let backTitle = " "
        _ = setTitleText(pageTitle)
        
        
        var imageName:String? = backImageNamed ?? TSColorConfigShared.navBackImageName
        _ = setNavigationItem(backTitle, imageName: imageName ?? "navi_back_white", direction: .left, action: #selector(navBarClickLeftAction))
    }

    public func setNavigationItem(_ name: String, imageName: String, direction: NSTextAlignment, action: Selector) -> UIButton {
        if direction == .left {
            return normalNavBarView.setLeftNavigationItem(name: name, imageName: imageName, target: self, action: action)
        } else {
            return normalNavBarView.setRightNavigationItem(name: name, imageName: imageName, target: self, action: action)
        }
    }

    @objc open func navBarClickLeftAction() {
        debugPrint("navBarClickLeftAction -> \(type(of: self))")
        pop()
    }

    @objc public func pop() {
        if navigationController == nil {
            dismiss(animated: true, completion: nil)
        } else if navigationController?.presentingViewController != nil, navigationController?.viewControllers.count == 1 {
            navigationController?.dismiss(animated: true, completion: nil)
        } else {
            navigationController?.popViewController(animated: true)
        }
    }

}


extension TSBaseVC {
    
    public func setNavBarViewHidden(_ isHidden: Bool) {
        navBarContentView.snp.updateConstraints { make in
            make.height.equalTo(isHidden ? 0 : k_Nav_Height)
        }
        
        contentView.snp.updateConstraints { make in
            make.top.equalTo(isHidden ? 0 : k_Nav_Height)
        }
    }
    
    public var isViewVisible: Bool {
        return isViewLoaded && view.window != nil && presentedViewController == nil
    }
    
    public func addPullDownClosePage() {
        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handleDismissPan(_:)))
        view.addGestureRecognizer(panGesture)
    }

    // 手势处理方法
     @objc public func handleDismissPan(_ gesture: UIPanGestureRecognizer) {
        let translation = gesture.translation(in: view)
        let progress = translation.y / view.bounds.height
        
        switch gesture.state {
        case .changed:
            view.transform = CGAffineTransform(translationX: 0, y: max(0, translation.y))
        case .ended:
            if progress > 0.5 || gesture.velocity(in: view).y > 1000 {
                dismiss(animated: true)
            } else {
                UIView.animate(withDuration: 0.3) {
                    self.view.transform = .identity
                }
            }
        default:
            break
        }
    }
}

extension TSBaseVC {
    
    public func addContentScrollView() {
        contentView.addSubview(contentScrollView)
        contentScrollView.addSubview(contentScrollViewContent)
        
        contentScrollView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        contentScrollViewContent.snp.makeConstraints { make in
             make.edges.equalToSuperview()
             make.width.equalToSuperview()
             make.height.equalTo(k_ScreenHeight-k_Nav_Height)
        }

    }
}
